<template>
  <view>
    <view class="top-fixed">
      <view class="top-search clearfix">
        <u-icon name="search" size="32" color="#fb5904"></u-icon>
        <input
          class="top-input"
          confirm-type="search"
          placeholder-class="input-pl"
          placeholder="商铺名称、负责人"
          type="text"
          v-model="search_form.name"
          @confirm="getData"
        />
        <u-icon
          v-show="search_form.name"
          @click="clearKeyword"
          class="icon-close"
          name="close"
          size="32"
          color="#999"
        ></u-icon>
      </view>
      <view class="search-sel">
        <view class="search-sel-li">
          <StatusSel @pickerChange="pickerStatusChange">
            <text class="sel-label sel-name" v-if="statuName">{{
              statuName
            }}</text>
            <text class="sel-label" v-else>状态</text>
            <u-icon
              class="ic-down"
              name="arrow-down"
              size="32"
              color="#999"
            ></u-icon>
          </StatusSel>
        </view>
        <view class="search-sel-li">
          <StatusSel @pickerChange="shopChange" :options="shopTypeList">
            <text class="sel-label sel-name" v-if="shopTypeName">{{
              shopTypeName
            }}</text>
            <text class="sel-label" v-else>经营方式</text>
            <u-icon
              class="ic-down"
              name="arrow-down"
              size="32"
              color="#999"
            ></u-icon>
          </StatusSel>
        </view>
      </view>
    </view>
    <view class="container-view">
      <scroll-view
        :lower-threshold="42"
        @scrolltolower="scrollLoading"
        scroll-y
        class="list-ul"
      >
        <!-- 替换 uni-swipe-action -->
        <view v-for="(item, index) in shop_list" :key="item.id || index">
          <view class="list-item clearfix" @click="checkSupplier(item, index)">
            <view class="float_left sel-view" v-if="source === 2">
              <i class="ibonfont ibonxuanze" v-if="!item.checked"></i>
              <i class="ibonfont ibonxuanze_xuanzhong" v-else></i>
            </view>
            <view :class="[source === 2 ? 'float_left' : '']">
              <view class="list-label clearfix">
                <view class="float_left list-name">{{ item.name }}</view>
                <view class="float_right status-text">{{
                  item.enableStatus === 5 ? "启用" : "禁用"
                }}</view>
              </view>
              <view class="list-cont clearfix">
                <view class="float_left">
                  <i class="ibonfont ibonkehu"></i>
                  {{ item.contactName || "--" }}
                </view>
                <view class="float_left" style="padding-left: 40rpx">
                  <i class="ibonfont ibonyingyeshijianzidingyi"></i>
                  <text v-if="item.openTime && item.openTime.isAllDay === 1"
                    >全天</text
                  >
                  <text v-else>
                    {{ (item.openTime && item.openTime.start) || "00:00" }}--{{
                      (item.openTime && item.openTime.end) || "23:59"
                    }}
                  </text>
                </view>
                <view
                  class="float_right mobile"
                  @click.stop="phoneCall(item.mobile)"
                >
                  <i class="ibonfont ibondianhua"></i>
                  {{ item.mobile }}
                </view>
              </view>
              <view class="address-view">
                <i class="ibonfont ibonlocation"></i>
                <template
                  v-if="
                    item.area &&
                    (item.area.provinceName ||
                      item.area.cityName ||
                      item.area.districtName ||
                      item.area.address)
                  "
                >
                  <span v-if="item.area.provinceName">{{
                    item.area.provinceName
                  }}</span>
                  <span v-if="item.area.cityName">
                    <template v-if="item.area.provinceName">-</template
                    >{{ item.area.cityName }}
                  </span>
                  <span v-if="item.area.districtName">
                    <template
                      v-if="item.area.provinceName || item.area.cityName"
                      >-</template
                    >{{ item.area.districtName }}
                  </span>
                  <span v-if="item.area.address">
                    <template
                      v-if="
                        item.area.provinceName ||
                        item.area.cityName ||
                        item.area.districtName
                      "
                      >-</template
                    >{{ item.area.address }}
                  </span>
                </template>
              </view>
            </view>
          </view>
        </view>
        <!-- 替换 uni-load-more -->
        <view v-show="loading_status !== 'noMore'">
          <text>{{
            loading_status === "loading" ? "加载中..." : "加载完毕"
          }}</text>
        </view>
        <view style="height: 120rpx" v-if="source === 2"></view>
      </scroll-view>
    </view>
    <view class="fixed-bottom" v-if="source === 2"
      ><view class="sub-btn" @click="selConfirm">确定</view></view
    >
    <!-- 替换 uni-popup -->
    <view v-if="showPersonPopup" class="personBack">
      <view class="form-label">更换负责人</view>
      <view class="form-view">
        <view class="form-item form-pa20 clearfix">
          <view class="form-label float_left">负责人</view>
          <!-- @click="goPage('/pagesB/systemSet/Partnership?source=1')" -->
          <!-- {
          "path": "systemSet/Partnership",
          "style": {
            "navigationBarTitleText": "合伙人"
          }
        } -->
          <view class="form-value float_right">
            <text class="input-pl" v-if="!form.partnerName">请选择</text>
            <text v-else>{{ form.partnerName }}</text>
            <i class="ibonfont ibonjinru icon-jinru"></i>
          </view>
        </view>
      </view>
      <view class="form-view">
        <view class="handel-view">
          <view class="btn-li float_left dis-btn" @click="cancelGoods">
            <i class="ibonfont ibonjinyong"></i>
            取消
          </view>
          <view class="btn-li float_right" @click="confirmGoods">
            <i class="ibonfont ibonqiyong"></i>
            确定
          </view>
        </view>
      </view>
    </view>
    <block>
      <!-- <block v-if="!shop_list.length || enterpriseScope === 5"> -->
      <view
        class="float-add-btn"
        @click="goPage('/pagesB/systemSet/AddShop')"
        v-if="accessCheck('ShopListSearch')"
      >
        <text>添加商铺</text>
      </view>
    </block>
  </view>
</template>

<script>
import StatusSel from "@/components/StatusSel.vue";
import addBtn from "@/components/AddData.vue";

export default {
  components: {
    "status-sel": StatusSel,
    "add-btn": addBtn,
  },
  data() {
    return {
      form: {
        partnerName: "",
      },
      enterpriseScope: 5,
      shop_list: [],
      pageSize: 10,
      page: 1,
      pageTotal: 0,
      statuName: "",
      shopTypeName: "",
      search_form: {
        name: "",
        shopPartnerId: "",
        shopType: "",
        enableStatus: "",
      },
      loading_status: "noMore",
      shopTypeList: [
        { value: "", label: "全部" },
        { value: 1, label: "联营商铺" },
        { value: 2, label: "直营商铺" },
      ],
      shopId: "",
      shopPartnerId: "",
      PartnershipSel: "",
      options: [],
      source: "",
      showPersonPopup: false, // 新增用于控制弹窗显示
    };
  },
  onLoad(options) {
    this.enterpriseScope = this.$store.state.enterpriseScope;
    this.initSwipeOptions();
    this.source = parseInt(options.source) || 0;
    this.getData();
  },
  onPullDownRefresh() {
    this.getData();
  },
  onNavigationBarButtonTap() {
    if (this.shop_list.length || this.enterpriseScope === 5) {
      if (!this.accessCheck("ShopListSearch")) {
        this.$u.toast("没有权限");
        return;
      }
      this.goPage("/pagesB/systemSet/AddShop");
    } else {
      this.$u.toast("店铺已存在，无需新增");
    }
  },
  onShow() {
    if (this.PartnershipSel) {
      this.shopPartnerId = this.PartnershipSel.id;
      this.form.partnerName = this.PartnershipSel.name;
    }
    this.getData();
  },
  methods: {
    accessCheck(key) {
      // 兼容不同权限对象写法
      const access =
        this.$Access ||
        (this.$store && this.$store.state && this.$store.state.Access);
      if (!access) return false;
      return this.$accessCheck(access[key]);
    },
    initSwipeOptions() {
      this.options = [];
      if (this.accessCheck("ShopListEditShop")) {
        this.options.push({
          text: "编辑",
          style: { backgroundColor: "#f5f5f5", color: "#666666" },
        });
      }
      if (this.accessCheck("ShopListDelShop")) {
        this.options.push({
          text: "删除",
          style: { backgroundColor: "rgb(255,58,49)" },
        });
      }
      if (this.accessCheck("ShopListChangeManagerForShop")) {
        this.options.push({
          text: "更换负责人",
          style: { backgroundColor: "#E6A23C" },
        });
      }
    },
    cancelGoods() {
      this.showPersonPopup = false;
    },
    async confirmGoods() {
      const { err } = await this.$u.api.changeManagerForShop({
        id: this.shopId,
        shopPartnerId: this.shopPartnerId,
      });
      if (err) return;
      this.$u.toast("更换成功");
      this.showPersonPopup = false;
      this.getData();
    },
    pickerStatusChange(row) {
      this.statuName = row.value !== "" ? row.label : "";
      this.search_form.enableStatus = row.value;
      this.getData();
    },
    shopChange(row) {
      this.shopTypeName = row.value !== "" ? row.label : "";
      this.search_form.shopType = row.value;
      this.getData();
    },
    scrollLoading() {
      if (this.pageTotal / this.pageSize > this.page) {
        this.page += 1;
        this.getData();
      } else {
        this.loading_status = "noMore";
      }
    },
    phoneCall(phone) {
      if (!phone) return;
      uni.makePhoneCall({ phoneNumber: phone });
    },
    checkSupplier(item, index) {
      // 修复item为undefined的问题
      // 1. item 可能为 undefined，index 也可能为 undefined
      // 2. 若item为undefined，尝试通过index从shop_list获取
      if (
        !item &&
        typeof index === "number" &&
        this.shop_list &&
        this.shop_list[index]
      ) {
        item = this.shop_list[index];
      }
      if (parseInt(this.source) === 1) {
        if (!item || !item.id) {
          this.$u && this.$u.toast && this.$u.toast("请选择有效的商铺");
          return;
        }
        this._prePage().shopData = item;
        uni.$emit("shop-selected", item);
        uni.navigateBack();
      } else if (parseInt(this.source) === 2) {
        if (!item) return;
        this.$set(item, "checked", !item.checked);
      }
    },
    selConfirm() {
      if (parseInt(this.source) === 2) {
        const arr = this.shop_list.filter((item) => item.checked);
        this._prePage().shopData = arr;
        this._prePage().shopSel = arr;
        uni.navigateBack();
      }
    },
    clearKeyword() {
      this.search_form.name = "";
      this.getData();
    },
    async searchData() {
      this.loading_status = "loading";
      const { err, data, pageTotal } = await this.$u.api.shopSearch({
        name: this.search_form.name,
        shopType: this.search_form.shopType,
        enableStatus: this.search_form.enableStatus,
        page: this.page,
        pageSize: this.pageSize,
      });
      this.loading_status = "noMore";
      uni.stopPullDownRefresh();
      if (err) return;
      const arr = Array.isArray(data) ? data : [];
      const cData = arr.map((item) => ({
        ...item,
        checked: false,
        openTime: item.openTime || {},
        area: item.area || {},
      }));
      if (this.page === 1) {
        this.shop_list = cData;
      } else {
        this.shop_list = this.shop_list.concat(cData);
      }
      this.pageTotal = pageTotal || 0;
    },
    //  获取列表
    async getAllShop() {
      this.loading_status = "loading";
      const { err, data, pageTotal } = await this.$u.api.getAllShop({
        page: this.page,
        pageSize: this.pageSize,
      });
      this.loading_status = "noMore";
      uni.stopPullDownRefresh();
      if (err) return;
      const arr = Array.isArray(data) ? data : [];
      const cData = arr.map((item) => {
        return {
          ...item,
          checked: false,
        };
      });
      if (this.page === 1) {
        this.shop_list = cData;
      } else {
        this.shop_list = this.shop_list.concat(cData);
      }
      this.pageTotal = pageTotal;
    },
    getData() {
      this.page = 1;
      this.getList();
    },
    getList() {
      const isKey = this.$utils.isSerch(this.search_form);
      if (isKey) {
        this.searchData();
      } else {
        this.getAllShop();
      }
    },
    deleteCartItem(e, item) {
      const text = e.text;
      if (text === "编辑") {
        this.goPage("/pagesB/systemSet/AddShop?id=" + item.id);
      } else if (text === "删除") {
        uni.showModal({
          title: "提示",
          content: "你确定删除此商铺吗?",
          success: async (res) => {
            if (res.confirm) {
              uni.showLoading();
              const { err, data } = await this.$u.api.delShop(item.id);
              uni.hideLoading();
              if (err) return;
              this.getData();
            }
          },
        });
      } else {
        this.shopId = item.id;
        this.showPersonPopup = true;
      }
    },
    goPage(url) {
      uni.navigateTo({ url });
    },
  },
};
</script>

<style lang="scss">
$uni-color-primary: #dd524d;
$uni-color-error: #ff3a31;

.container-view {
  /* #ifdef H5*/
  height: calc(100vh - 230upx);
  /* #endif */
  /* #ifdef MP||APP-PLUS */
  height: calc(100vh - 138upx);
  /* #endif */
  // transform: translateY(138upx);
  background: #fff;
  padding-top: 10px;
}

.top-fixed {
  background: #fff;
  box-shadow: 0 2upx 8upx rgba(221, 82, 77, 0.08);
  padding-bottom: 16upx;
}

.top-search {
  display: flex;
  align-items: center;
  padding: 20upx 24upx;
  background: #fff;
  border-bottom: 1upx solid #f5f5f5;

  .top-input {
    flex: 1;
    margin: 0 16upx;
    padding: 12upx 20upx;
    border-radius: 32upx;
    border: 1upx solid #eee;
    background: #f9f9f9;
    font-size: 28upx;
    color: #333;
  }
  .icon-close {
    margin-left: 8upx;
    color: #bbb;
  }
}

.input-pl {
  color: #bbb;
}

.search-sel {
  display: flex;
  padding: 12upx 24upx 0 24upx;
  background: #fff;

  .search-sel-li {
    flex: 1;
    margin-right: 16upx;
    background: #f9f9f9;
    border-radius: 24upx;
    padding: 8upx 20upx;
    display: flex;
    align-items: center;
    justify-content: center;
    min-width: 0;

    &:last-child {
      margin-right: 0;
    }

    .sel-label {
      font-size: 26upx;
      color: #666;
      margin-right: 8upx;
      &.sel-name {
        color: $uni-color-primary;
        font-weight: 500;
      }
    }
    .ic-down {
      margin-left: 4upx;
    }
  }
}

.list-ul {
  background: #fff;
  min-height: 400upx;
}

.list-item {
  padding: 32upx 24upx 24upx 24upx;
  border-bottom: 1upx solid #f5f5f5;
  background: #fff;
  transition: background 0.2s;
  &:active {
    background: #fbeceb;
  }
}

.list-label {
  margin-bottom: 12upx;
  .list-name {
    font-size: 32upx;
    color: #222;
    font-weight: 600;
  }
  .status-text {
    font-size: 24upx;
    color: $uni-color-primary;
    padding: 0 12upx;
    border-radius: 8upx;
    background: #fbeceb;
  }
}

.list-cont {
  display: flex;
  align-items: center;
  margin-bottom: 8upx;

  .ibonkehu {
    font-size: 26upx;
    margin-right: 10upx;
    color: $uni-color-primary;
  }
  .ibonyingyeshijianzidingyi {
    font-size: 26upx;
    margin-right: 10upx;
    color: $uni-color-primary;
  }
  .mobile {
    color: $uni-color-primary;
    font-weight: 500;
    cursor: pointer;
  }
}

.sel-view {
  margin-right: 20upx;
  color: #999;
  font-size: 30upx;

  .ibonxuanze_xuanzhong {
    color: $uni-color-primary;
  }
}

.address-view {
  font-size: 24upx;
  color: #666;
  padding-top: 10upx;
  display: flex;
  align-items: center;

  .ibonlocation {
    font-size: 26upx;
    margin-right: 10upx;
    color: $uni-color-primary;
  }
}

.fixed-bottom {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  box-shadow: 0 -2upx 8upx rgba(221, 82, 77, 0.08);
  z-index: 10;
  padding: 24upx 0;
  .sub-btn {
    width: 90%;
    margin: 0 auto;
    background: $uni-color-primary;
    color: #fff;
    font-size: 32upx;
    text-align: center;
    border-radius: 40upx;
    height: 80upx;
    line-height: 80upx;
    font-weight: 600;
    box-shadow: 0 4upx 16upx rgba(221, 82, 77, 0.12);
  }
}

.personBack {
  background: #ffffff;
  padding: 30upx;
  border-radius: 24upx;
  box-shadow: 0 8upx 32upx rgba(221, 82, 77, 0.08);
  .form-label {
    font-size: 30upx;
    color: $uni-color-primary;
    font-weight: 600;
    margin-bottom: 24upx;
  }
}

.form-view {
  padding: 0;
}

.form-item {
  margin-bottom: 24upx;
  .form-label {
    font-size: 28upx;
    color: #333;
  }
  .form-value {
    color: $uni-color-primary;
    font-size: 28upx;
    display: flex;
    align-items: center;
    cursor: pointer;
    .icon-jinru {
      font-size: 28upx;
      margin-left: 8upx;
      color: #bbb;
    }
  }
}

.handel-view {
  display: flex;
  width: 100%;
  margin-top: 16upx;

  .btn-li {
    flex: 3;
    text-align: center;
    background: $uni-color-primary;
    height: 70upx;
    line-height: 70upx;
    margin-right: 20upx;
    color: #fff;
    border-radius: 16upx;
    font-size: 28upx;
    font-weight: 500;
    cursor: pointer;

    .ibonfont {
      margin-right: 20upx;
    }
  }

  .btn-li:last-child {
    margin-right: 0;
  }

  .dis-btn {
    background: #f4f4f4;
    color: #999;
  }

  .del-btn {
    background: $uni-color-error;
  }
}

// 新增浮动按钮样式
.float-add-btn {
  position: fixed;
  right: 40upx;
  bottom: 120upx;
  z-index: 999;
  display: flex;
  align-items: center;
  background: #fb5904;
  color: #fff;
  border-radius: 50upx;
  padding: 0 32upx 0 20upx;
  height: 80upx;
  box-shadow: 0 4upx 16upx rgba(221, 82, 77, 0.18);
  font-size: 30upx;
  cursor: pointer;
  transition: background 0.2s;
  .u-icon {
    margin-right: 12upx;
  }
  &:active {
    background: #e04c00;
  }
}
</style>
